
$(function () {
  let token = null
  //获取token值
  async function fn() {
    const data = await axios.post('http://124.223.14.236:3001/api/user/login', {
      username: "tv",
      password: "123456"
    })
    token = data.data.data.token
  } fn()
  const lis = document.querySelectorAll('.cate-list-fix li')


  //列表渲染
  axios.get('http://124.223.14.236:3001/api/goods/cate').then(({ data }) => {
    data.data.map((element, i) => {
      for (let index = 0; index < lis.length; index++) {
        if (i === index) {
          lis[index].innerHTML = element.name
        }
      }
    })

  })

  //分类颜色切换
  for (let j = 0; j < lis.length; j++) {
    lis[j].addEventListener('click', function () {
      document.querySelector('.active').classList.remove('active')
      this.classList.add('active')
      fns(j + 1)
    })
  }

  //获取对应分类的数据
  async function fns(j) {

    const data = await axios.get(`http://124.223.14.236:3001/api/goods?cate_id=${j}`)
    const lists = data.data.data.list
    console.log(lists);
    let htmlStr = lists.map((element) => {
      return `
                              <li data-id='${element.id}' id='${element.cate_id}'>
                                  <img src="${element.img}" alt="">
                                    <h3>${element.title}</h3>
                                      <p>
                                          <span class="price">￥${(element.price) / 10}</span>
                                          <span class="add" data-price='${(element.price) / 100}'>+</span>
                                      </p>
                               </li>
                                 `


    }).join('')
    document.querySelector('.good-list ul').innerHTML = htmlStr

    fnsAdd()
  } fns(1)

  //添加商品到购物车
  function fnsAdd() {
    const list = document.querySelectorAll('.add')
    const liAll = document.querySelectorAll('.good-list li')
    for (let i = 0; i < list.length; i++) {
      list[i].addEventListener('click', async function () {

        var data = {
          title: liAll[i].children[1].innerHTML,
          img: liAll[i].children[0].src,
          price: +list[i].dataset.price,
          goods_id: +liAll[i].dataset.id,
          cate_id: +liAll[i].id,
          buy_num: 1,
          is_selected: 1,
        }
        
        const res = await axios.post('http://124.223.14.236:3001/api/cart/create', data, {
          headers: {
            Authorization: token
          }
        })
        if (res.status !== 200) return alert(res.statusText)
        alert(res.data.msg)
      })
    }
  }
})